/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb.common;

import entity.Reparto;
import facade.RepartoFacade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Valerio
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class RepartoManager implements RepartoManagerLocal {

    @EJB
    private RepartoFacade repartoFacade;
    @PersistenceContext(unitName = "E-Market-ejbPU")
    private EntityManager em;

    @Override
    public void creaReparto(Reparto r) {

        Query q = em.createNamedQuery("reparto.cercaPerNome");
        q.setParameter(1, r.getNome());

        if (!q.getResultList().isEmpty()) {

            return;
        }

        repartoFacade.create(r);
    }// creaReparto

    @Override
    public void rimuoviReparto(Reparto r) {

        Query q = em.createNamedQuery("reparto.cercaPerNome");
        q.setParameter(1, r.getNome());

        if (q.getResultList().isEmpty()) {

            return;
        }

        repartoFacade.remove(r);
    }// rimuoviReparto

    @Override
    public Reparto cercaPerNome(String nome) {

        Query q = em.createNamedQuery("reparto.cercaPerNome");

        q.setParameter(1, nome);
        
        List<Reparto> list=q.getResultList();

        return (list.isEmpty())? null : list.get(0);
    }// cercaPerNome

    @Override
    public Reparto cercaPerId(Long id) {

        Reparto reparto = repartoFacade.find(id);
        return reparto;
    }// cercaPerId

    @Override
    public void modificaReparto(Reparto r) {

        Query q = em.createNamedQuery("reparto.cercaPerNome");
        q.setParameter(1, r.getNome());

        if (q.getResultList().isEmpty()) {
            return;
        }
        repartoFacade.edit(r);

    }// modificaReparto

    @Override
    public List<Reparto> cercaTutto() {

        List<Reparto> rep = repartoFacade.findAll();
        return rep;
    }// cercaTutto

    public void persist(Object object) {
        em.persist(object);
    }

    @Override
    public List<Reparto> getRepartiFromNegozioConFornitura(Long negozioID) {
        Query q=em.createNamedQuery("reparto.repartiProdottiFornitiDalNegozio");
        q.setParameter(1, negozioID);
        return q.getResultList();
    }
}
